package com.pair.micro.back.security.event;

import com.pair.micro.back.common.utils.IPUtils;
import com.pair.micro.back.modules.sys.enums.LoginOperationEnum;
import com.pair.micro.back.modules.sys.service.SysLogLoginService;
import com.pair.micro.common.constant.Constant;
import com.pair.micro.common.security.user.UserDetail;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 认证事件处理
 *
 * @author xubz
 *
 */
@Component
@AllArgsConstructor
public class AuthenticationEvents {
    private final SysLogLoginService sysLogLoginService;

    @EventListener
    public void onSuccess(AuthenticationSuccessEvent event) {
        // 用户信息
        UserDetail user = (UserDetail) event.getAuthentication().getPrincipal();

        sysLogLoginService.save(user.getUsername(), Constant.SUCCESS, LoginOperationEnum.LOGIN_SUCCESS.getValue());
        // 保存登录日志
//        sysLogLoginService.save(user.getUsername(), Constant.SUCCESS, LoginOperationEnum.LOGIN_SUCCESS.getValue());
        //SysLogEntity sysLog = new SysLogEntity();
        //sysLog.setOperation("登录成功");
        //sysLog.setMethod("login");
        //sysLog.setUsername(user.getUsername());
        //sysLog.setCreateDate(new Date());
        //sysLogService.save(sysLog);
    }

    @EventListener
    public void onFailure(AbstractAuthenticationFailureEvent event) {
        // 用户名
        String username = (String) event.getAuthentication().getPrincipal();

        sysLogLoginService.save(username, Constant.FAIL, LoginOperationEnum.ACCOUNT_FAIL.getValue());
        // 保存登录日志
//        sysLogLoginService.save(username, Constant.FAIL, LoginOperationEnum.ACCOUNT_FAIL.getValue());
        //SysLogEntity sysLog = new SysLogEntity();
        //sysLog.setOperation("登录失败");
        //sysLog.setMethod("login");
        //sysLog.setUsername(username);
        //sysLog.setCreateDate(new Date());
        //sysLogService.save(sysLog);
    }

}